package com.example.environment;

import com.example.exception.EmptyException;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

/**
 * @author wangbin
 */
@RestController
@RequestMapping("/environment")
public class EnvironmentController {
    @Resource
    private EnvironmentRepository environmentRepository;

    @GetMapping
    public List<Environment> list() {
        return environmentRepository.findAllFetch();
    }

    @GetMapping("/{id}")
    public Environment getOne(@PathVariable Long id) {
        Optional<Environment> environment = environmentRepository.findById(id);
        return environment.orElseThrow(EmptyException::new);
    }

    @PostMapping
    public void save(@RequestBody Environment environment) {
        environment.getList().forEach(s -> s.setEnvironment(environment));
        environmentRepository.save(environment);
    }

    @DeleteMapping("/{id}")
    public void delete(@PathVariable Long id) {
        environmentRepository.deleteById(id);
    }
}
